/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ch.haclyon.driveimageview.driveimageview.fraction;

import ch.haclyon.driveimageview.driveimageview.DisplayItemAdapter;
import ch.haclyon.driveimageview.driveimageview.ResourceTable;
import ch.haclyon.driveimageview.driveimageview.slice.MainAbilitySlice;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.ListContainer;

import java.util.ArrayList;
import java.util.Arrays;

/**
 * MainFraction
 *
 * @author wangyin
 * @since 2021/07/19
 */
public class MainFraction extends Fraction {
    /**
     * callBack
     */
    private CallBack callBack;
    /**
     * displayItemAdapter
     */
    private DisplayItemAdapter displayItemAdapter;

    /**
     * setCallBack
     *
     * @param callBack callBack
     */
    public void setCallBack(CallBack callBack) {
        this.callBack = callBack;
    }

    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        Component component = scatter.parse(ResourceTable.Layout_fraction_main, container, false);
        ListContainer listContainer = (ListContainer) component.findComponentById(ResourceTable.Id_listContainer);
        displayItemAdapter = new DisplayItemAdapter(
                new ArrayList<>(Arrays.asList(MainAbilitySlice.sampleTexts)), getFractionAbility()
        );
        listContainer.setItemProvider(displayItemAdapter);
        listContainer.setItemClickedListener((listContainer1, component1, i, l) -> callBack.entryDetail(i));
        return component;
    }

    @Override
    protected void onActive() {
        super.onActive();
        getFractionAbility().getUITaskDispatcher().delayDispatch(new Runnable() {
            @Override
            public void run() {
                if (displayItemAdapter != null) {
                    displayItemAdapter.notifyDataChanged();
                }
            }
        }, 50);
    }

    /**
     * CallBack
     */
    public interface CallBack {
        /**
         * entryDetail
         *
         * @param position position
         */
        void entryDetail(int position);
    }
}
